<template>
  <div class="wg-login">
    <mt-field label="用户名" placeholder="请输入用户名" v-model="username"></mt-field>
    <div ref="val1" style="display: none; background: #00bcd4; color: white; text-align: center; width: 100%; height:30px; line-height:30px">用户名格式错误</div>
    <mt-field label="密码" placeholder="请输入密码" type="password" v-model="password"></mt-field>
    <div ref="val2" style="display: none; background: #00bcd4; color: white; text-align: center; height:30px; line-height: 30px">密码格式错误</div>
    <mt-button type='primary' size="large" class="login" @click='login'>登录</mt-button>
  </div>
</template>

<script>
import {
  mapState,
  mapMutations
} from 'vuex'

import {
  Toast
} from 'mint-ui'

export default {
  name: 'Login',
  data () {
    return {
      username: '',
      password: '',
      loginsuc: [false, false]
    }
  },
  watch: {
    userInfo (userInfo) {
      if (userInfo.isLogin === true) {
        const { redirect = '/home' } = this.$route.params
        this.$router.push(redirect)
      }
    },
    username () {
      let reg = /^[a-zA-Z0-9_-]{4,16}$/
      if (!reg.test(this.username)) {
        this.$refs.val1.style.display = 'block'
        this.loginsuc[0] = false
      } else {
        this.$refs.val1.style.display = 'none'
        this.loginsuc[0] = true
      }
    },
    password () {
      let reg = /^[\w_-]{6,16}$/
      if (!reg.test(this.password)) {
        this.$refs.val2.style.display = 'block'
        this.loginsuc[1] = false
      } else {
        this.$refs.val2.style.display = 'none'
        this.loginsuc[1] = true
      }
    }
  },
  methods: {
    ...mapMutations(['getuserinfo']),
    login () {
      if (this.loginsuc[0] === false || this.loginsuc[1] === false) {
        Toast('请输入正确的格式')
        return false
      } else {
        this.$http.post('http://rap2api.taobao.org/app/mock/117548/api/login', {
          username: this.username,
          password: this.password
        })
          .then(resp => {
            this.getuserinfo(resp.data.data)
            alert('登陆成功')
            this.$router.push('/cart')
          })
      }
    }
  },
  computed: {
    ...mapState(['userInfo'])
  }
}
</script>

<style lang="scss">
.login {
  margin-top: 20px;
}
.wg-login-img {
  width: 100%;
  height: auto;
  margin: 50px auto;

  .item-img2 {
    display: block;
    margin: 0px auto;
    width: 50%;
    height: auto;
  }
}
</style>>
